package com.kyd.api.gateway.filter;

import com.kyd.api.gateway.feign.AuthService;
import com.kyd.api.gateway.support.GateWayExchangeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @author zhuangqi
 * @date 2019-03-27
 */
@Component
public class TokenFilter implements GlobalFilter, Ordered {

    @Autowired
    private AuthService authService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        if (GateWayExchangeUtils.isPassRouted(exchange)) {
            return chain.filter(exchange);
        }
        //token校验
        boolean tokenVerify = false;
        List<String> authorizations = exchange.getRequest().getHeaders().get("Authorization");
        if (!ObjectUtils.isEmpty(authorizations)) {
            String token = authorizations.get(0);
            tokenVerify = authService.verify(token).getData();
        }
        if (!tokenVerify) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }


    @Override
    public int getOrder() {
        return 1;
    }


}
